//
//  Dados.m
//  iFarmacia
//
//  Created by Fabio Valencio on 09/01/11.
//  Copyright 2011 PontoMobi. All rights reserved.
//

#import "Dados.h"


@implementation Dados

@synthesize arrFarm;


-(id) init {
	if (self = [super init]) {
		arrDados = [[NSMutableArray alloc] init];
	}
	return self;
}


- (void)dealloc {
	
	[arrDados release];
    [super dealloc];
}

-(NSMutableArray*) readFarmFromDatabase{
	databaseName = @"farm_05.sql"; 
	
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
	
	// Setup the database object
	sqlite3 *database;
	
	arrDados = [[NSMutableArray alloc] init];
	
	NSString *sql;
	
	//NSLog(@"Acessando Base de Dados");
	
	if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		
		sql = [NSString stringWithFormat:@"SELECT * FROM tb_farmacia"];
		
		const char *sqlStatement = [sql UTF8String];
		sqlite3_stmt *compiledStatement;
		
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
			
			//NSLog(@"SQL OK");
			
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				//NSLog(@"SQL OK");
				NSString *aId			= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
				NSString *aNome			= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
				NSString *aLL			= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
				
				Farm *farmObj			= [[Farm alloc] init];
				farmObj.farmID			= aId;
				farmObj.farmNome		= aNome;
				farmObj.farmLLString	= aLL;
				
				[arrDados addObject:farmObj];
				[farmObj release];
				
			}
		}else {
			NSLog(@"Erro: ");
		}
	}
	
	return arrDados;
}


@end
